package threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * # @File  : SingleThreadPool.java
 * # @Author: Lomo
 * # @Site  : lomo.space
 * # @Date  : 2021-09-01
 * # @Desc  : newSingleThreadExecutor
 * 单线程的线程池，线程异常结束，会创建一个新的线程，能确保任务按提交顺序执行
 *
 * 适用：按顺序执行任务的场景
 */
public class SingleThreadPool {
    private static ExecutorService singleExecutor = Executors.newSingleThreadExecutor();

    public static void main(String[] args) {
        testSingleExecutor();
    }

    //测试单线程的线程池
    private static void testSingleExecutor() {
        for (int i = 0; i < 3; i++) {
            final int index = i;
            singleExecutor.execute(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " index:" + index);
                }
            });
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("3秒后...");

        singleExecutor.shutdown();
    }
}
